//! 循环控制示例
//!
//! Rust 有三种循环：loop、while 和 for

/// loop 循环示例
///
/// loop 关键字告诉 Rust 一遍又一遍地执行一段代码，直到你明确要求停止
#[test]
pub fn loop_basics() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2; // 使用 break 返回值
        }
    };

    println!("loop 循环结果: {result}");
}

/// 嵌套循环和循环标签
///
/// 可以为循环添加标签，用于在多层循环中控制跳出
#[test]
pub fn nested_loops() {
    let mut count = 0;

    // 添加循环标签
    'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break; // 跳出内层循环
            }

            if count == 2 {
                break 'counting_up; // 跳出外层循环
            }

            remaining -= 1;
        }

        count += 1;
    }

    println!("循环结束,count = {count}");
}

/// while 循环示例
///
/// while 循环在条件为真时执行
#[test]
pub fn while_loop() {
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }

    println!("倒计时结束！");
}

/// for 循环示例
///
/// for 循环用于遍历集合
#[test]
pub fn for_loop() {
    let a = [10, 20, 30, 40, 50];

    // 遍历数组
    for element in a {
        println!("数组元素: {element}");
    }

    // 使用 range 遍历
    println!("正向计数:");
    for number in 1..=3 {
        println!("{number}!");
    }

    // 反向遍历
    println!("倒计时:");
    for number in (1..4).rev() {
        println!("{number}!");
    }

    println!("发射！");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_loop_basics() {
        loop_basics();
    }

    #[test]
    fn test_while_loop() {
        while_loop();
    }

    #[test]
    fn test_for_loop() {
        for_loop();
    }
}
